import { AgentOptions, DefaultPostHeaders } from "./Config";
import request = require('request');

export default class HttpManager {
    private static _ins: HttpManager;
    public static get Ins() {
        return this._ins = this._ins ? this._ins : new HttpManager();
    }
    get(url: string, options) {
        return new Promise<string>((resolve, reject) => {
            options = options || {};
            let httpOptions = {
                url: url,
                method: 'get',
                timeout: 3000,
                headers: options.headers || DefaultPostHeaders,
                proxy: options.proxy || '',
                agentOptions: AgentOptions
            }
            request.get(httpOptions, (err: any, res: request.Response, body: string) => {
                if (err) {
                    reject(err);
                } else {
                    if (res.statusCode == 200) {
                        resolve(body);
                    } else {
                        reject(res.statusCode);
                    }
                }
            }).on('error', console.error);
        });
    }

    post(url: string, postdata, options) {
        return new Promise<string>((resolve, reject) => {
            options = options || {};
            let httpOptions = {
                url: url,
                body: JSON.stringify(postdata),
                method: 'post',
                timeout: options.timeout || 3000,
                headers: options.headers || DefaultPostHeaders,
                proxy: options.proxy || '',
                agentOptions: AgentOptions
            };
            request(httpOptions, (err: any, res: request.Response, body: string) => {
                if (err) {
                    reject(err);
                } else {
                    if (res.statusCode == 200) {
                        resolve(body);
                    } else {
                        reject(res.statusCode);
                    }
                }
            }).on('error', console.error);
        });
    }
}